<template>
	<view class="row-wrap" :class="[extraClass || '']" :style="extraStyle || ''">
		<view
			v-for="(el, i) in mediaData"
			class="flex-center relative text-hide mr-3-1 mb-3-1"
			:key="i"
			:style="(i + 1) % 3 === 0 ? 'margin-right:0' : ''"
		>
			<image
				v-if="el.isImg"
				:src="el.src"
				mode="aspectFill"
				class="rounded-l"
				style="width: 212rpx; height: 212rpx"
				@click="previewImg(el)"
			/>
			<video v-else :src="el.src" style="width: 300rpx; height: 450rpx" :poster="poster" />
			<view
				class="absolute text-hide flex-center"
				style="width: 60rpx; height: 60rpx; top: -30rpx; right: -30rpx"
				:class="[uploading ? 'opacity-50' : '']"
				@click="removeImg(i)"
			>
				<view class="bg-active rounded-full flex-center" style="width: 36rpx; height: 36rpx">
					<text class="iconfont icon-close color-white text-xs"></text>
				</view>
			</view>
		</view>
		<view
			class="flex-column flex-center rounded-s bg-color-2 mb-3-1"
			:class="[uploading ? 'opacity-50' : '']"
			@click="startChoose"
			v-if="mediaData.length < maxNum"
			style="width: 212rpx; height: 212rpx"
		>
			<view class="mb-2"> <i class="iconfont icon-tianjia color-active" style="font-size: 70rpx"></i> </view>
			<view>
				<text class="text-xn color-secondary">{{ uploading ? '上传中...' : '上传' }}</text>
			</view>
		</view>
		<action-sheet ref="actionSheet" :btns="btns" @clickBtn="clickBtn" v-if="supportVideo" />
	</view>
</template>

<script>
import { ref, getCurrentInstance, watch } from 'vue';
import { getAuthHeader } from '@/uni-sdk/request/request.js';
import { isImgFile, getExt } from '@/uni-sdk/utils/media.js';
import setting from './setting.js';
const MAX_IMG_SIZE = 20 * 1024 * 1024;
const MAX_VIDEO_SIZE = 20 * 1024 * 1024;
const MAX_IMG_NUM = 9;

export default {
	props: {
		extraClass: String,
		extraStyle: String,
		disabled: Boolean,
		supportVideo: Boolean,
		num: {
			default: MAX_IMG_NUM,
			type: Number,
		},
		url: String,
		extraParam: Object,
		//选择图片后马上上传
		uploadImmediate: Boolean,
	},
	setup(props, ctx) {
		const actionSheet = ref();
		const maxNum = ref(props.num);
		const poster = ref('');
		let _thumbTempFilePath = null;
		const mediaData = ref([]);
		const uploading = ref(false);
		watch(
			mediaData,
			(val) => {
				ctx.emit('change', val);
			},
			{
				deep: true,
			}
		);
		const btns = ref([
			{ name: '选择视频', close: true },
			{ name: '选择图片', close: true },
		]);
		function clickBtn({ index }) {
			if (index === 0) {
				maxNum.value = 1;
				uni.chooseVideo({
					count: 1,
					success(e) {
						const { thumbTempFilePath, tempFilePath, size } = e;
						if (size > MAX_VIDEO_SIZE) {
							return getApp().globalData.toast('请选择少于20M的视频', true);
						}
						_thumbTempFilePath = thumbTempFilePath;
						mediaData.value = [
							{
								src: tempFilePath,
							},
						];
					},
				});
			} else {
				if (_thumbTempFilePath) {
					//不能同时含图片和视频
					_thumbTempFilePath = null;
					mediaData.value = [];
				}
				maxNum.value = props.num;
				const len = mediaData.value.length;
				uni.chooseImage({
					count: maxNum.value - len,
					success: selectImgCallBack,
				});
			}
		}
		async function selectImgCallBack(e) {
			const tempFiles = e.tempFiles;
			const imgData = [];
			let isOver = false;
			try {
				const sysInfo = uni.getSystemInfoSync();
				const maxWidth = sysInfo.screenWidth * 1.5;
				for (let i = 0, item; (item = tempFiles[i++]); ) {
					let path = item.path;
					if (item.size <= MAX_IMG_SIZE) {
						//对图片进行缩放 减少大小
						let ext = null;
						let re = await uni.getImageInfo({ src: path });
						const originType = re.type;
						if (re.width > maxWidth) {
							re = await uni.compressImage({ src: path, width: maxWidth + 'px' });
							path = re.tempFilePath;
							let fileExt = getExt(path);
							if (fileExt && fileExt.length > 1) {
								ext = null;
							} else {
								ext = originType;
							}
						}
						const mediaItem = {
							src: path,
							isImg: true,
							ext,
						};
						if (props.uploadImmediate) {
							uploading.value = true;
							const uploadRe = await uploadMedia(mediaItem);
							if (uploadRe) {
								imgData.push({
									src: uploadRe.url,
									isImg: true,
									ext,
								});
							} else {
							}
							uploading.value = false;
						} else {
							imgData.push(mediaItem);
						}
					} else {
						isOver = true;
					}
				}
			} catch (ex) {
				console.log('selectImg error', ex);
			}
			if (isOver) {
				getApp().globalData.toast('请选择少于5M的图片', true);
			}
			mediaData.value = mediaData.value.concat(imgData);
		}
		function startChoose() {
			const len = mediaData.value.length;
			if (props.disabled || len >= maxNum.value || uploading.value) return;
			if (props.supportVideo) {
				actionSheet.value.open();
			} else {
				uni.chooseImage({
					count: maxNum.value - len,
					success: selectImgCallBack,
				});
			}
		}
		function previewImg(el) {
			uni.previewImage({
				urls: [el.src],
			});
		}
		function removeImg(i) {
			if (props.disabled || uploading.value) return;
			mediaData.value.splice(i, 1);
		}
		function isSelect(unShowMes) {
			let len = mediaData.value.length;
			if (len === 0) {
				!unShowMes &&
					getApp().globalData.toast(props.supportVideo ? '请至少选择一张图片或一个视频' : '请至少选择一张图片', true);
				return false;
			}
			return true;
		}
		async function uploadMedia(mediaItem) {
			let resp = null;
			try {
				const uploadUrl = props.url || setting.defaultUrl;
				const uploadParam = {
					url: uploadUrl,
					filePath: mediaItem.src,
					name: 'file',
					header: getAuthHeader(),
				};
				uploadParam.formData = Object.assign({ ...setting.defaultParams }, props.extraParam || {});
				resp = await uni.uploadFile(uploadParam);
				if (resp) {
					let data = JSON.parse(resp.data);
					if (data.code === 0) {
						// successNum++;
						let url = data.data;
						// result.push(data);
						console.log('upload success', url);
						let thumbUrl = '';
						if (_thumbTempFilePath) {
							resp = await uni.uploadFile({
								url: uploadUrl,
								filePath: _thumbTempFilePath,
								name: 'file',
								header: getAuthHeader(),
							});
							data = JSON.parse(resp.data);
							if (data.code === 0) {
								thumbUrl = data.data;
							} else {
								console.log('upload thumb fail', resp, data);
							}
							// result.push(data.url);
						}
						return {
							url,
							thumbUrl,
						};
					} else {
						console.log('upload fail', data);
					}
				} else {
					console.log('upload fail resp is null');
				}
			} catch (ex) {
				console.log('upload fail', ex);
			}
			return false;
		}
		async function upload1by1() {
			let len = mediaData.value.length;
			if (len === 0) {
				return [];
			}
			if(props.uploadImmediate) {
				return mediaData.value.map((el) => el.src);
			}
			uploading.value = true;
			let successNum = 0;
			let failNum = 0;
			const result = [];
			for (let i = 0; i < len; i++) {
				const mediaItem = mediaData.value[i];
				if (mediaItem.isRemote) {
					successNum++;
					result.push(mediaItem.src);
					if (_thumbTempFilePath) {
						result.push(_thumbTempFilePath);
					}
				} else {
					const uploadRe = await uploadMedia(mediaItem);
					if (uploadRe) {
						successNum++;
						result.push(uploadRe.url);
						if (uploadRe.thumbUrl) {
							result.push(uploadRe.thumbUrl);
						}
					} else {
						failNum++;
					}
				}
				ctx.emit('upload', {
					index: i,
					sum: len,
				});
			}
			uploading.value = false;
			return result;
		}
		function setImgData(imgData) {
			if(!imgData) {
				mediaData.value = [];
				return;
			}
			let first = imgData[0];
			if (!first) {
				mediaData.value = [];
				return;
			}
			if (typeof first === 'string') {
				imgData = imgData.map((el) => ({ src: el }));
				first = imgData[0];
			}
			maxNum.value = props.num;
			_thumbTempFilePath = null;
			mediaData.value = imgData.map((el) => ({ src: el.src, isRemote: true, isImg: true }));
			// if (isImgFile(first.src)) {
			// 	maxNum.value = props.num;
			// 	//第一张是图片 说明全是图片
			// 	_thumbTempFilePath = null;
			// 	mediaData.value = imgData.map((el) => ({ src: el.src, isRemote: true, isImg: true }));
			// } else {
			// 	maxNum.value = 1;
			// 	_thumbTempFilePath = first.poster || (imgData[1] ? imgData[1].src : '');
			// 	poster.value = _thumbTempFilePath;
			// 	mediaData.value = [
			// 		{
			// 			src: first.src,
			// 			isRemote: true,
			// 		},
			// 	];
			// }
		}
		return {
			poster,
			maxNum,
			clickBtn,
			btns,
			mediaData,
			startChoose,
			previewImg,
			removeImg,
			isSelect,
			upload1by1,
			setImgData,
			actionSheet,
			uploading,
		};
	},
};
</script>

<style></style>
